﻿using Chen.CefWebKit.WebBrowser;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace Chen.CefWebKit
{
    public class TaskModel
    {
        BrowserTabUserControl TaskItem;
        public TaskStatus Status { get; protected set; }
        /// <summary>
        /// 名称
        /// </summary>
        public string Name { get; protected set; }
        private object _locker = new object();
        public TaskModel(string _name, BrowserTabUserControl _TaskItem)
        {
            Name = _name;
            TaskItem = _TaskItem;
        }
        /// <summary>
        /// 执行一个操作,只有当上一个操作完成后才可执行
        /// </summary>
        /// <param name="action"></param>
        /// <returns></returns>
        public async Task<int> DoTask(Func<BrowserTabUserControl, int> action, bool HasNextTask = false)
        {
            if (Status == TaskStatus.ERROR)//判断状态是否为错误 如果是错误直接返回-1
            {
                return await Task.Run(() => { return -1; });
            }
            var _status = TaskStatus.SLEEP;
            if (HasNextTask)//判断这个任务之后是否有其他相关任务。
            {
                _status = TaskStatus.WAITNEXT;
            }

            //如果任务正在运行。一直循环。
            await Task.Run(() => {
                while (Status == TaskStatus.RUNNING)
                {
                    Thread.Sleep(500);
                }
            });

            lock (_locker)
            {
                Status = TaskStatus.RUNNING;
            }
            return await Task.Run<int>(() => {
                try
                {
                    var result = action(TaskItem);
                    lock (_locker)
                    {
                        Status = _status;
                    }
                    return result;
                }
                catch
                {
                    lock (_locker)
                    {
                        Status = TaskStatus.ERROR;
                    }
                    return -1;
                }
            });
        }
        /// <summary>
        /// 获得任务绑定的浏览器标签页任务对象
        /// </summary>
        /// <returns></returns>
        public BrowserTabUserControl GetBrowser()
        {
            return TaskItem;
        }
    }
    public enum TaskStatus
    {
        INIT,
        RUNNING,
        WAITNEXT,
        SLEEP,
        ERROR
    }
}
